package com.atguigu.gmall.product.controller;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.service.TestService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "测试接口")
@RestController
@RequestMapping("admin/product/test")
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping("testLock")
    public Result testLock() {
        testService.testLock();
        return Result.ok();
    }


    /**
     * 读数据接口
     *
     * @return
     */
    @GetMapping("/read")
    public Result read() {
        String msg = testService.read();
        return Result.ok(msg);
    }

    /**
     * 写数据接口
     *
     * @return
     */
    @GetMapping("/write")
    public Result write() {
        testService.write();
        return Result.ok("写入数据成功");
    }


    /**
     * 写数据接口
     *
     * @return
     */
    @GetMapping("/testAsync")
    public Result testAsync() {
        testService.testAsync("a");
        log.info("web层testAsync方法.... ");
        return Result.ok("调用成功");
    }


    /**
     * 保存用户信息
     * 如果校验参数失败,将错误信息封装到对象
     *
     * @param bindingResult 只有校验参数失败 才有值
     * @param user
     * @return
     */
    @PostMapping("/saveUser")
    public Result saveUser(@Valid @RequestBody TestUserDTO user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //获取违规字段值
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            if (!CollectionUtils.isEmpty(fieldErrors)) {
                String error = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
                throw new RuntimeException(error);
            }
        }
        System.out.println("保存用户成功");
        return Result.ok();
    }


    //@PostMapping("/updateUser")
    //public Result updateUser(@RequestBody TestUserDTO user) {
    //
    //}

}
